package com.epro.dx.activity;

import java.util.ArrayList;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.epro.dx.R;
import com.epro.dx.adapter.BrowseListAdapter;
import com.epro.dx.util.AsyncTaskUtil;
import com.google.android.gms.analytics.HitBuilders;
import com.google.android.gms.analytics.Tracker;
import com.weipu.common.DXApplication;
import com.weipu.common.DXApplication.TrackerName;
import com.weipu.common.constants.ServerConstant;
import com.weipu.common.facade.content.api.BrowsingHistoryService;
import com.weipu.common.facade.exception.DxException;
import com.weipu.common.facade.factory.ProviderFactory;
import com.weipu.common.facade.model.OrderProductModel;
import com.weipu.common.facade.model.ProductModel;
import com.weipu.common.util.NetWorkUtil;
import com.weipu.common.util.StringUtil;

/**
 * 商品浏览历史记录
 * 
 * @author  hjd008
 * @version  [版本号, 2014-12-16]
 * @see  [相关类/方法]
 * @since  [产品/模块版本]
 */
public class BrowseAcitivty extends BaseFragmentActivity implements OnClickListener, OnItemClickListener,
    OnItemLongClickListener
{
    
    /**
     * 商品列表
     */
    private ListView listView;
    
    private TextView suggest;
    
    private ImageView suggestImageView;
    
    private BrowsingHistoryService browsingHistoryService = ProviderFactory.createBrowsingHistoryServiceDBProvider();
    
    /**
     * 客户端本地数据库中购物车对象列表
     */
    private ArrayList<OrderProductModel> browseHistoryList = new ArrayList<OrderProductModel>();
    
    /**
     * 列表适配器
     */
    private BrowseListAdapter nativebrowsAdapter;

	private Tracker tracker;
    
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        //集成GA
        tracker = ((DXApplication)getApplication()).getTracker(TrackerName.APP_TRACKER);
        // 不显示标题栏
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.nativeborwselist);
        setTitleContent(R.string.browse_history);
        setLeftBtnToHome(HomeActivity.titleArray[3]);
        initView();
        new BrowseHistorylistAsyncTask().execute();
    }
    
    @Override
	protected void onResume() {
		super.onResume();
		tracker.setScreenName("MyBrowseHistory");
		tracker.send(new HitBuilders.ScreenViewBuilder().build());
	}
	
	@Override
	protected void onPause() {
		super.onPause();
		tracker.setScreenName(null);
	}
    
    private void initView()
    {
    	 suggest=((TextView)findViewById(R.id.tv_empty));
    	 suggestImageView=((ImageView)findViewById(R.id.pic_empty));
        listView = (ListView)findViewById(R.id.nativeborwselist);
        listView.setOnItemClickListener(this);
        listView.setOnItemLongClickListener(this);
        
     // 填充适配器
		nativebrowsAdapter = new BrowseListAdapter(
				BrowseAcitivty.this, browseHistoryList, null,
				listView, true,getDensityDpi(),NetWorkUtil.isWifi(getApplicationContext()));
		// 设置适配器
		listView.setAdapter(nativebrowsAdapter);
		
		// 右上角初始化clear控件
		setRightBtnContent(R.string.title_clear)
				.setOnClickListener(BrowseAcitivty.this);
		retryBtn.setOnClickListener(this);
    }
    
    @Override
    public void onClick(View v)
    {
        //清空
        if (v.getId() == R.id.topbar_right_tv)
        {
            if (browseHistoryList == null || browseHistoryList.isEmpty())
            {
                return;
            }
            new AlertDialog.Builder(this).setPositiveButton(R.string.loading_confirm,
                new DialogInterface.OnClickListener()
                {
                    @Override
                    public void onClick(DialogInterface dialog, int which)
                    {
                        if (null != browseHistoryList && !browseHistoryList.isEmpty())
                        {
                            new DeleteBrowseHistoryItem().execute(-1);
                        }
                        else
                        {
                            dialog.dismiss();
                        }
                    }
                })
                .setTitle(R.string.title_clear)
                .setNegativeButton(R.string.btn_title_cancel, new DialogInterface.OnClickListener()
                {
                    
                    @Override
                    public void onClick(DialogInterface dialog, int which)
                    {
                        dialog.dismiss();
                    }
                })
                .setMessage(R.string.user_wish_confirm_clear)
                .show();
        }else if(v.getId() == R.id.try_again){//网络错误页面的重试按钮
        	AsyncTaskUtil.executeTask(new BrowseHistorylistAsyncTask());
        }
        
    }
    
    /**
     * 加载商品浏览记录
     * 
     * 
     * @author  qsc255
     * @version  [版本号, 2015-1-12]
     * @see  [相关类/方法]
     * @since  [产品/模块版本]
     */
    class BrowseHistorylistAsyncTask extends AsyncTask<Void, Void, String>
    {
        @Override
        protected void onPreExecute()
        {
//            showWaitingDialog();
        	showLoadingLayout(listView);
        }
        
        @Override
        protected String doInBackground(Void... params)
        {
        	browseHistoryList.clear();
            browseHistoryList.addAll(browsingHistoryService.selectMenusList(BrowseAcitivty.this, "_id desc"));
            try {
				refreshProducsByCurrencyCode();
			} catch (DxException e) {
				return e.getErrCode();
			}
            return "0";
        }
        
        @Override
        protected void onPostExecute(String result)
        {
			if (!isFinishing()) {
//				hideWaitingDialog();
                hideAllLayout(listView);
				if ("0".equals(result)) {
					if (browseHistoryList != null
							&& !browseHistoryList.isEmpty()) {
						hideAllLayout(listView);
    					topbarrightTv.setVisibility(View.VISIBLE);
    					nativebrowsAdapter.notifyDataSetChanged();
					} else {
						showEmptyLayout(listView, R.string.empty_history, R.drawable.no_history);
					}
				}else{
					if(ServerConstant.ReturnCode.CLIENT_NET_UN_AVAILABLE.equals(result)){
						showErrorLayout(listView, R.string.internet_error,
								R.string.internet_suggest, R.drawable.no_internet);
					}else{
						showErrorLayout(listView, R.string.server_busy,
								R.string.server_suggest, R.drawable.no_internet);
					}
					topbarrightTv.setVisibility(View.GONE);
				}
			}
        }
    }
    
    /**
     * 根据当前浏览商品ID号删除或者删除所有浏览记录
     * Integer -1 表删除所有
     * @author  qsc255
     * @version  [版本号, 2015-1-13]
     * @see  [相关类/方法]
     * @since  [产品/模块版本]
     */
    class DeleteBrowseHistoryItem extends AsyncTask<Integer, Void, String>
    {
        
        @Override
        protected void onPreExecute()
        {
//            showWaitingDialog();
        	showLoadingLayout(null);
            super.onPreExecute();
        }
        
        @Override
        protected String doInBackground(Integer... params)
        {
            
            if (params[0] != -1)
            {
                browsingHistoryService.deleteById(BrowseAcitivty.this, params[0]);
            }
            else
            {
                //清空所有
                browsingHistoryService.deleteTemplateBySelection(BrowseAcitivty.this, null, null);
            }
            // 调用接口更新数据
            browseHistoryList.clear();
            browseHistoryList.addAll(browsingHistoryService.selectMenusList(BrowseAcitivty.this, "_id desc"));
            try {
				refreshProducsByCurrencyCode();
			} catch (DxException e) {
				return e.getErrCode();
			}
            return "0";
        }
        
        @Override
        protected void onPostExecute(String result)
        {
        	if(!isFinishing()){
//    			hideWaitingDialog();
        		hideAllLayout(listView);
    			if("0".equals(result)){
    				if (null != browseHistoryList && !browseHistoryList.isEmpty())
    				{
    					hideAllLayout(listView);
    					topbarrightTv.setVisibility(View.VISIBLE);
    					nativebrowsAdapter.notifyDataSetChanged();
    				}
    				else if (null == browseHistoryList || browseHistoryList.isEmpty())
    				{
    					nativebrowsAdapter.notifyDataSetChanged();
    					showEmptyLayout(listView, R.string.empty_history, R.drawable.no_history);
    					topbarrightTv.setVisibility(View.GONE);
    				}
				}else{
    				showErrorLayout(listView,  R.string.internet_error, R.string.internet_suggest, R.drawable.no_internet);
            		topbarrightTv.setVisibility(View.GONE);
    			}
    		}
            super.onPostExecute(result);
        }
    }
    
    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id)
    {
        if (browseHistoryList.size() > position)
        {

            Intent intent = new Intent(BrowseAcitivty.this, DetailActivity.class);
            //FIXME
            Bundle data = new Bundle();
            data.putInt(ServerConstant.Parameter.PARAMETER_NAME_PRODUCT_ID, browseHistoryList.get(position).getSku());
            data.putString(ServerConstant.Parameter.PARAMETER_NAME_BACK_ACTION,
                ServerConstant.ActionConstant.ACTION_NATIVEBROWSELIST);
            data.putString(ServerConstant.Parameter.PARAMETER_NAME_FROM_ACTIVITY,
                ServerConstant.ActionConstant.ACTION_NATIVEBROWSELIST);
            intent.putExtras(data);
            startActivity(intent);
        }
        
    }
    
    /**
     * 根据本地存储的CurrencyCode刷新产品列表的信息
     * @throws DxException 
     */
    private void refreshProducsByCurrencyCode() throws DxException{
    	ArrayList<ProductModel> products =null;
    	if (browseHistoryList != null&& !browseHistoryList.isEmpty()){
        	//获取本地保存的货币简写，调用接口切换为显示选中的货币价格信息
    		String currencyCode = StringUtil.getConfig(ServerConstant.Parameter.PARAMETER_NAME_CURRENCYCODE,
    						getString(R.string.currency_default_currencyCode));
    		ArrayList<Integer> skus = new ArrayList<Integer>();
    		for(int i = 0;i<browseHistoryList.size();i++){
    			skus.add(browseHistoryList.get(i).getSku());
    		}
    		products = ProviderFactory.createCurrencyServiceProvider().switchCurrencyCode(skus, currencyCode);
			//更新价格等信息
			if(products!=null&&products.size()>0){
				for(int i = 0;i<browseHistoryList.size();i++){
					for(int j=0;j<products.size();j++){
						if(browseHistoryList.get(i).getSku()==products.get(j).getSku()){
							browseHistoryList.get(i).setCurrencyCode(products.get(j).getCurrencyCode());
							browseHistoryList.get(i).setCurrencyCodeSymbol(products.get(j).getCurrencyCodeSymbol());
							browseHistoryList.get(i).setPrice(products.get(j).getPrice());
							break;
						}
					}
				}
			}
        }
    }
    
    @Override
    public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id)
    {
        final OrderProductModel cartItem = (OrderProductModel)nativebrowsAdapter.getItem(position);
        new AlertDialog.Builder(BrowseAcitivty.this).setTitle(R.string.delete)
            .setCancelable(true)
            .setMessage(R.string.user_wish_confirm_del)
            .setPositiveButton(R.string.btn_title_ok, new DialogInterface.OnClickListener()
            {
                @Override
                public void onClick(DialogInterface dialog, int which)
                {
                    new DeleteBrowseHistoryItem().execute(cartItem.getId());
                }
            })
            .setNegativeButton(R.string.btn_title_cancel, new DialogInterface.OnClickListener()
            {
                @Override
                public void onClick(DialogInterface dialog, int which)
                {
                    dialog.cancel();
                }
            })
            .create()
            .show();
        return true;
    }
    
    @Override
    protected void onDestroy() {
//    	if(null!=nativebrowsAdapter){
//    		nativebrowsAdapter.recleBitmap();
//    	}
    	super.onDestroy();
    }
    
}
